package org.wedding.system.service.impl;

import cn.dev33.satoken.stp.SaLoginConfig;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yitter.idgen.YitIdHelper;
import com.google.protobuf.ServiceException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.wedding.center.entity.NoticeInfo;
import org.wedding.center.service.NoticeInfoService;
import org.wedding.constant.CommonConst;
import org.wedding.enums.system.ResultCodeEnum;
import org.wedding.system.dto.menu.MenuTreeDto;
import org.wedding.system.dto.user.UserQuery;
import org.wedding.system.entity.MenuEntity;
import org.wedding.system.entity.RoleEntity;
import org.wedding.system.mapper.RoleMapper;
import org.wedding.system.mapper.UserMapper;
import org.wedding.system.service.IUserService;
import org.wedding.system.util.WxUtils;
import org.wedding.utils.*;
import org.wedding.center.constant.Constant;
import org.wedding.center.dto.AuthUserDto;
import org.wedding.system.entity.UserInfo;
import org.wedding.center.entity.ApprovalInfo;
import org.wedding.center.entity.CouponInfo;
import org.wedding.center.entity.RightInfo;
import org.wedding.center.service.ApprovalInfoService;
import org.wedding.center.service.CouponInfoService;
import org.wedding.center.service.RightInfoService;
import org.wedding.center.util.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import cn.hutool.core.util.ObjectUtil;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * UserServiceImpl
 *
 * @author yh_liu
 * @version v1.0
 * @since 2022/11/13
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl extends ServiceImpl<UserMapper, UserInfo> implements IUserService {
    private final RedisUtil redisUtil;
    @Value("${wx.appid}")
    private String appid;
    @Value("${wx.secret}")
    private String secret;
    @Value("${userDefault.password}")
    private String passwordDefault;
    @Resource
    private ApprovalInfoService approvalInfoService;
    @Resource
    private QiniuUtils qiniuUtils;
    @Resource
    private CouponInfoService couponInfoService;
    @Resource
    private RightInfoService rightInfoService;
    @Resource
    private UserMapper userMapper;
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private NoticeInfoService noticeInfoService;


    public UserServiceImpl(RedisUtil redisUtil) {
        this.redisUtil = redisUtil;
    }

    @Override
    public List<MenuTreeDto> getUserMenu(String userId) {
//        List<MenuEntity> menuEntities = baseMapper.getUserMenu(userId, "c");
//        if (CollectionUtils.isNotEmpty(menuEntities)) {
//            TreeNodeConfig config = new TreeNodeConfig();
//            return TreeUtil.build(menuEntities, "999999", config,
//                    (object, tree) -> {
//                        tree.setName(object.getName());
//                        tree.setId(object.getId());
//                        tree.setWeight(StrUtil.isEmpty(object.getSort()) ? 0 : Integer.parseInt(object.getSort()));
//                        tree.setParentId(object.getParentId());
//                        tree.putExtra("component", object.getComponent());
//                        tree.putExtra("path", object.getPath());
//                        tree.setName(
//                                object.getPath().startsWith("/") ?
//                                        object.getPath().substring(1) :
//                                        object.getPath());
//                        tree.putExtra("meta", object.getMeta());
//                        tree.putExtra("redirect", "");
//                    });
//        } else {
//            return new ArrayList<>();
//        }

        List<MenuEntity> menuList = baseMapper.getUserMenu(userId, "c");
        List<MenuTreeDto> menuTreeDtoList = BeanUtil.copyToList(menuList, MenuTreeDto.class);
        //List<MenuTreeDto> data = menuTreeDtoList.stream().sorted(Comparator.comparing(MenuTreeDto::getSort)).collect(Collectors.toList());
        return new TreeUtil<MenuTreeDto>().buildTree(menuTreeDtoList, "999999");
    }

    @Override
    public CommonResult delUser(String userId) {
        //先删除用户关联的数据
        roleMapper.delRoleUserByUserId(userId);
        baseMapper.delUserTenant(userId);
        baseMapper.deleteById(userId);
        return CommonResult.success();
    }

    @Override
    public void insertUserTenant(String id, String tenant, String user) {
        baseMapper.insertUserTenant(id, tenant, user);
    }

    @Override
    public void insertRoleUser(String id, String role, String user) {
        roleMapper.delRoleUserByUserIdAndRole(role, id);
        roleMapper.insertRoleUser(id, role, user, DateUtil.now());
    }

    @Override
    public List<UserInfo> listAll(UserQuery query) {
        List<UserInfo> list = baseMapper.listAll(query);
        return query.setList(PageUtil.getListPage(query.getCurrent(), query.getPageSize(), list), list.size());
    }

    @Override
    @Transactional
    public CommonResult updateUser(UserInfo userDto) {
        UserInfo userEntity = new UserInfo();
        userEntity.setUserName(userDto.getUserName());
        userEntity.setNickName(userDto.getNickName());
        userEntity.setPhone(userDto.getPhone());
        userEntity.setEmail(userDto.getEmail());
        userEntity.setId(userDto.getId());
        userEntity.setOrgan(userDto.getOrgan());

        //处理用户关联机构
        if (StrUtil.isNotEmpty(userDto.getTenant())) {
            baseMapper.delUserTenant(userDto.getId());
            baseMapper.insertUserTenant(String.valueOf(YitIdHelper.nextId()), userDto.getTenant(), userDto.getId());
        }
        if (StrUtil.isNotEmpty(userDto.getRoles())) {
            //处理用户关联角色
            roleMapper.delRoleUserByUserId(userDto.getId());
            String[] roles = userDto.getRoles().split(CommonConst.STRING_COMMA);
            for (String role : roles) {
                RoleEntity roleEntity = roleMapper.selectById(role);
                if (ObjectUtil.isNotEmpty(roleEntity)) {
                    if ("普通用户".equals(roleEntity.getName())) {
                        userDto.setRole("0");
                    } else if ("商家".equals(roleEntity.getName())) {
                        userDto.setRole("1");
                    } else if ("管理员".equals(roleEntity.getName())) {
                        userDto.setRole("2");
                    }
                }
                roleMapper.insertRoleUser(String.valueOf(YitIdHelper.nextId()), role, userDto.getId(), DateUtil.now());
            }
        }
        if (StrUtil.isNotEmpty(userDto.getRole())) {
            String roleName = "普通用户";
            if ("1".equals(userDto.getRole())) {
                roleName = "商家";
            } else if ("2".equals(userDto.getRole())) {
                roleName = "管理员";
            }
            RoleEntity role = roleMapper.findByName(roleName);
            if (ObjectUtil.isNotEmpty(role)) {
                //重新插入用户角色关联关系
                roleMapper.delRoleUserByUserIdAndRole(role.getId(), userDto.getId());
                roleMapper.insertRoleUser(String.valueOf(YitIdHelper.nextId()), role.getId(), userDto.getId(), DateUtil.now());
            }
        }
        baseMapper.updateById(userEntity);
        return CommonResult.success();
    }


    /**
     * 分页查询所有数据
     *
     * @param query
     * @return
     */
    @Override
    public CommonResult<List<UserInfo>> findAll(UserQuery query) {
        try {
            LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
            if (StrUtil.isNotEmpty(query.getNickName())) {
                queryWrapper.like(UserInfo::getNickName, query.getNickName());
            }
            if (StrUtil.isNotEmpty(query.getStatus())) {
                queryWrapper.eq(UserInfo::getStatus, query.getStatus());
            }
            if (StrUtil.isNotEmpty(query.getTenant())) {
                queryWrapper.eq(UserInfo::getTenant, query.getTenant());
            }
            Page<UserInfo> page = new Page<>(query.getCurrent(), query.getPageSize());
            IPage<UserInfo> iPage = this.page(page, queryWrapper);
            List<UserInfo> userInfos = query.setList(iPage.getRecords(), iPage.getTotal());
            return CommonResult.success(userInfos);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(ResultCodeEnum.API_ERROR);
        }
    }

    /**
     * 根据id查看详情
     *
     * @param id
     * @return
     */
    @Override
    public CommonResult<UserInfo> view(String id) {
        try {
            UserInfo userInfo = baseMapper.findById(id);
            return CommonResult.success(userInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(ResultCodeEnum.API_ERROR);
        }
    }

    /**
     * 新增数据
     *
     * @param userInfo
     * @return
     */
    @Override
    public CommonResult add(UserInfo userInfo) {
        try {
            if (StrUtil.isEmpty(userInfo.getNickName()) && StrUtil.isNotEmpty(userInfo.getUserName())) {
                userInfo.setNickName(userInfo.getUserName());
            }
            if (StrUtil.isEmpty(userInfo.getUserName()) && StrUtil.isNotEmpty(userInfo.getNickName())) {
                userInfo.setUserName(userInfo.getNickName());
            }
            userInfo.setId(IdUtil.simpleUUID());
            userInfo.setCreateTime(DateUtil.now());
            userInfo.setIsDeleted("0");
            userInfo.setStatus("0");
            //生成唯一的邀新二维码
            Set<String> invitationCodes = baseMapper.findInvitationCodes();
            String invitationCode = InvitationCodeGenerator.generateCodeData(invitationCodes);
            userInfo.setInvitedCode(invitationCode);
            baseMapper.insert(userInfo);
            //查询系统权限
            RightInfo rightInfo = rightInfoService.findOne().getData();
            if (!ObjectUtil.isEmpty(rightInfo)) {
                if ("0".equals(rightInfo.getIsDiscount())) {
                    //优惠卷开关打开
                    List<CouponInfo> useType = couponInfoService.findByUseType();
                    if (!useType.isEmpty()) {
                        //给新用户发放优惠券
                        for (CouponInfo couponInfo : useType) {
                            couponInfo.setType("1");
                            couponInfo.setUserId(userInfo.getId());
                            couponInfoService.add(couponInfo);
                        }
                    }
                }
            }
            //若填写了邀请码 那需记录邀请人id并为邀请人的邀请新人数+1
            if (StrUtil.isNotEmpty(userInfo.getInvitedCode())) {
                UserInfo user = baseMapper.findByInvitedCode(userInfo.getInvitedCode());
                if (ObjectUtil.isEmpty(user)) {
                    return CommonResult.failed(1, "该邀请码不存在");
                }
                userInfo.setInvitedId(user.getId());
                int invitedNew = Integer.parseInt(user.getInvitedNew());
                user.setInvitedNew(String.valueOf(invitedNew + 1));
                baseMapper.updateById(user);
                //拉新-通知邀请人
                noticeInfoService.add(NoticeInfo.builder()
                        .userId(user.getId())
                        .userName(user.getUserName())
                        .notice("您已成功邀请一位用户！")
                        .type("3")
                        .quality("middle")
                        .creator(StpUtil.getLoginIdAsString())
                        .build());
            }

//            couponInfoService.addYhq(userInfo.getId());
            return CommonResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(ResultCodeEnum.API_ERROR);
        }
    }

    /**
     * 修改数据
     *
     * @param userInfo
     * @return
     */
    @Override
    @Transactional
    public CommonResult updateEntity(UserInfo userInfo) {
        try {
            if (StrUtil.isEmpty(userInfo.getId())) {
                return CommonResult.failed(ResultCodeEnum.PARAM_ERROR);
            }
            userInfo.setUpdateTime(DateUtil.now());
            //商家注册
            if ("1".equals(userInfo.getRole())) {
                //新建审批申请
                ApprovalInfo approvalInfo = new ApprovalInfo();
                approvalInfo.setBusinessType("0");
                approvalInfo.setBusinessId(userInfo.getId());
                approvalInfo.setApprover("1");
                approvalInfo.setApproverName("system");
                approvalInfo.setCreator(userInfo.getId());
                approvalInfo.setCreatorName(userInfo.getUserName());
                CommonResult result = approvalInfoService.add(approvalInfo);
                if (result.getCode() != 0) {
                    return result;
                }
                //默认新商家用户的入驻状态为审核中
                userInfo.setSettleIn("0");
            }
            if (StrUtil.isNotEmpty(userInfo.getRole())) {
                String roleName = "普通用户";
                if ("1".equals(userInfo.getRole())) {
                    roleName = "商家";
                } else if ("2".equals(userInfo.getRole())) {
                    roleName = "管理员";
                }
                RoleEntity role = roleMapper.findByName(roleName);
                if (ObjectUtil.isNotEmpty(role)) {
                    //重新插入用户角色关联关系
                    roleMapper.delRoleUserByUserIdAndRole(role.getId(), userInfo.getId());
                    roleMapper.insertRoleUser(String.valueOf(YitIdHelper.nextId()), role.getId(), userInfo.getId(), DateUtil.now());
                }
            }
            baseMapper.updateById(userInfo);
            return CommonResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(ResultCodeEnum.API_ERROR);
        }
    }

    /**
     * 更新用户审批状态
     *
     * @param approvalInfo
     * @return
     */
    @Override
    @Transactional
    public CommonResult updateUserApproval(ApprovalInfo approvalInfo) {
        try {
            //审批商家入住
            CommonResult result = approvalInfoService.updateEntity(approvalInfo);
            if (result.getCode() != 0) {
                return result;
            }
            baseMapper.updateUserApproval(approvalInfo.getBusinessId(), approvalInfo.getStatus());
            return CommonResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(ResultCodeEnum.API_ERROR);
        }
    }


    /**
     * 删除数据
     *
     * @param ids
     * @return
     */
    @Override
    public CommonResult delete(List<String> ids) {
        try {
            if (ObjectUtil.isEmpty(ids)) {
                return CommonResult.failed(ResultCodeEnum.PARAM_ERROR);
            }
            for (String id : ids) {
                baseMapper.upDeleteById(id);
            }
            return CommonResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(ResultCodeEnum.API_ERROR);
        }
    }

    @Override
    public UserInfo getInfoByUserName(String userName) {
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getUserName, userName);
        return this.getOne(queryWrapper);
    }

    @Override
    public List<String> getUserMenuAuth(String userId) {
        List<MenuEntity> menuEntities = baseMapper.getUserMenu(userId, "b");
        return menuEntities.stream().map(MenuEntity::getAuthCode).collect(Collectors.toList());
    }

    @Override
    public List<String> getUserRole(String userId) {
        return baseMapper.getUserRole(userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<UserInfo> login(AuthUserDto authUserDto, HttpServletRequest request) {
        try {
            // 通过缓存判断同一IP某一时间段内的登录次数是否超出限定次数
            String ip = NetworkUtils.getIp(request);
            String requestLoginIp = "request_login_".concat(ip);
            long loginCount = redisUtil.increment(requestLoginIp, 1L);
            if (loginCount == 1) {
                redisUtil.expire(requestLoginIp, Constant.REQUEST_LOGIN_LIMIT_TIME);
            }
            if (loginCount > Constant.REQUEST_LOGIN_LIMIT_COUNT) {
                log.warn("IP:[".concat(ip).concat("]已超出限定次数"));
                return CommonResult.failed(1, "您的操作过于频繁，请稍后再试");
            }


            //authType=1代表是微信登录
            if (ObjectUtil.isNotEmpty(authUserDto.getAuthType()) && authUserDto.getAuthType() == 1) {
                String paramStr = String.format("appid=%s&secret=%s&js_code=%s&grant_type=authorization_code", appid, secret, authUserDto.getCode());

                //调用微信端授权认证接口
                String wxResult = HttpRequest.get("https://api.weixin.qq.com/sns/jscode2session?" + paramStr)
                        .header("Content-Type", "application/json;charset=UTF-8")
                        .execute().body();
                if (wxResult == null) {
                    return CommonResult.failed(1, "调用微信端授权认证接口错误");
                }

                JSONObject wxJson = new JSONObject(wxResult);
                String openId = wxJson.getStr(Constant.OPEN_ID);
                String sessionKey = wxJson.getStr(Constant.SESSION_KEY);
                String unionId = wxJson.getStr(Constant.UNION_ID);
                if (org.springframework.util.StringUtils.isEmpty(openId)) {
                    return CommonResult.failed(1, wxJson.getStr(Constant.ERR_MSG));
                }
                authUserDto.setOpenId(openId);
                String phoneNumber = WxUtils.getPhoneNumber(authUserDto.getPhoneCode(), appid, secret);
                if (StringUtils.isEmpty(phoneNumber)) {
                    throw new ServiceException("手机号获取失败");
                }
                //判断用户表中是否存在该用户，不存在则进行解密得到用户信息，并进行新增用户
                UserInfo selectOne = baseMapper.selectOne(Wrappers.<UserInfo>lambdaQuery().eq(UserInfo::getOpenId, openId).eq(UserInfo::getPhone, phoneNumber));
                if (ObjectUtil.isEmpty(selectOne)) {
                    String userData = WeChatUtil.decryptData(authUserDto.getEncryptedData(), sessionKey, authUserDto.getIv());
                    if (org.springframework.util.StringUtils.isEmpty(userData)) {
                        return CommonResult.failed(1, "解密用户信息错误");
                    }

                    JSONObject userJson = new JSONObject(userData);
                    String nickName = userJson.getStr(Constant.NICK_NAME);
                    String avatarUrl = userJson.getStr(Constant.AVATAR_URL);

                    UserInfo user = new UserInfo();
                    user.setUserName(nickName);
                    if (StrUtil.isEmpty(nickName)) {
                        List<String> names = userMapper.selectAllName();
                        String numberName = getNumberName(names, 6);
                        user.setUserName("微信用户" + numberName);
                    }
                    user.setIconUrl(avatarUrl);
                    user.setOpenId(openId);
                    user.setPhone(phoneNumber);
                    user.setUnionId(unionId);
                    user.setRole("0");
                    this.getDefaultPassword(user);
                    this.add(user);
                    authUserDto.setUserInfo(user);
                } else {
                    authUserDto.setUserInfo(selectOne);
                }
            }

            //authType=0代表是用户名登录
            if (!org.springframework.util.StringUtils.isEmpty(authUserDto.getAuthType()) && authUserDto.getAuthType() == 0) {

                String userName = authUserDto.getUserName();
                //判断用户表中是否存在该用户，不存在则进行解密得到用户信息，并进行新增用户
                UserInfo resultUser = baseMapper.selectOne(Wrappers.<UserInfo>lambdaQuery().eq(UserInfo::getUserName, userName));
                if (ObjectUtil.isEmpty(resultUser)) {
                    return CommonResult.failed(1, "该用户不存在");
                } else {
                    String password = DigestUtils.md5DigestAsHex((authUserDto.getPassword() + resultUser.getSalt()).getBytes());
                    if (!password.equals(resultUser.getPassWord())) {
                        return CommonResult.failed(1, "密码错误");
                    }
                    authUserDto.setUserInfo(resultUser);
                }
            }

            //authType=2代表是手机号登录
            if (!org.springframework.util.StringUtils.isEmpty(authUserDto.getAuthType()) && authUserDto.getAuthType() == 2) {

                String phone = authUserDto.getPhone();
                //判断用户表中是否存在该用户，不存在则进行解密得到用户信息，并进行新增用户
                UserInfo resultUser = baseMapper.selectOne(Wrappers.<UserInfo>lambdaQuery().eq(UserInfo::getPhone, phone));
                if (ObjectUtil.isEmpty(resultUser)) {
                    return CommonResult.failed(1, "该用户不存在");
                } else {
                    String password = DigestUtils.md5DigestAsHex((authUserDto.getPassword() + resultUser.getSalt()).getBytes());
                    if (!password.equals(resultUser.getPassWord())) {
                        return CommonResult.failed(1, "密码错误");
                    }
                    authUserDto.setUserInfo(resultUser);
                }
            }
            UserInfo userInfo = authUserDto.getUserInfo();
            userInfo.setLoginDate(DateUtil.date());
            updateEntity(userInfo);
            // 所有验证通过后开始登录
            StpUtil.login(userInfo.getId(), SaLoginConfig.setDevice(authUserDto.getDevice()).
                    setExtraData(BeanUtil.beanToMap(authUserDto.getUserInfo())));
            // 登录后获取token信息
            String token = StpUtil.getTokenValue();
            if (StrUtil.isNotEmpty(userInfo.getUserName())) {
                StpUtil.getSession().set("userName", userInfo.getUserName());
            }
            if (StrUtil.isNotEmpty(userInfo.getId())) {
                StpUtil.getSession().set("userId", userInfo.getId());
            }
            if (StrUtil.isNotEmpty(userInfo.getRole())) {
                StpUtil.getSession().set("role", userInfo.getRole());
            }
            if (StrUtil.isNotEmpty(userInfo.getNickName())) {
                StpUtil.getSession().set("nickName", userInfo.getNickName());
            }
            if (StrUtil.isNotEmpty(userInfo.getOpenId())) {
                StpUtil.getSession().set("openId", userInfo.getOpenId());
            }
            // 将当前用户信息写入Redis缓存
            String key = Constant.EMPTY_CACHE + token;
            redisUtil.setDay(key, userInfo.getId(), 1);
            userInfo.setToken(token);
            //登录成功-更新优惠卷信息
            CommonResult result = couponInfoService.expired();
            if (result.getCode() != 0) {
                return result;
            }
            return CommonResult.success(authUserDto.getUserInfo());
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(ResultCodeEnum.API_ERROR);
        }
    }

    public String getNumberName(List<String> collect_numbers, int length) {
        String number = cn.hutool.core.util.RandomUtil.randomNumbers(length);
        if (collect_numbers.contains(number)) {
            return this.getNumberName(collect_numbers, length);
        } else {
            return number;
        }
    }

    /**
     * 用户注册-添加新用户
     *
     * @param userInfo
     * @return
     */
    @Override
    public CommonResult<UserInfo> register(UserInfo userInfo) {
        try {
            if ((StrUtil.isEmpty(userInfo.getPhone()) && StrUtil.isEmpty(userInfo.getUserName())) || StrUtil.isEmpty(userInfo.getPassWord())) {
                return CommonResult.failed(1, "请使用正确的用户名或手机号登录，密码不能为空");
            }
            if (StrUtil.isEmpty(userInfo.getPhone())) {
                UserInfo selectOne = baseMapper.selectOne(Wrappers.<UserInfo>lambdaQuery().eq(UserInfo::getUserName, userInfo.getUserName()));
                if (ObjectUtil.isNotEmpty(selectOne)) {
                    return CommonResult.failed(1, "该用户名已注册");
                }
            } else {
                UserInfo selectOne = baseMapper.selectOne(Wrappers.<UserInfo>lambdaQuery().eq(UserInfo::getPhone, userInfo.getPhone()));
                if (ObjectUtil.isNotEmpty(selectOne)) {
                    return CommonResult.failed(1, "该手机号已注册");
                }
            }
            if (StrUtil.isNotEmpty(userInfo.getRole())) {
                //商家注册
                if ("1".equals(userInfo.getRole())) {
                    //默认新商家用户为不推荐用户
                    userInfo.setIsRecommend("1");
                    //新建审批申请
                    ApprovalInfo approvalInfo = new ApprovalInfo();
                    approvalInfo.setBusinessType("0");
                    approvalInfo.setBusinessId(userInfo.getId());
                    approvalInfo.setApprover("1");
                    approvalInfo.setApproverName("system");
                    CommonResult result = approvalInfoService.add(approvalInfo);
                    if (result.getCode() != 0) {
                        return result;
                    }
                    //默认新商家用户的入驻状态为审核中
                    userInfo.setSettleIn("0");
                }
            }
            //生成随机盐值并对密码进行加密
            this.getDefaultPassword(userInfo);
            this.add(userInfo);
            return CommonResult.success(userInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(ResultCodeEnum.API_ERROR);
        }
    }

    /**
     * 获取当前登录用户信息
     *
     * @param request
     * @return
     */
    @Override
    public CommonResult<UserInfo> getUserInfo(HttpServletRequest request) {
        String userId = AuthUtils.getUserId();
        UserInfo userInfo = baseMapper.findById(userId);
        if (ObjectUtil.isNotEmpty(userInfo)) {
            return CommonResult.success(userInfo);
        }
        return CommonResult.success();
    }

    /**
     * 退出登录
     *
     * @param request
     * @return
     */
    @Override
    public CommonResult<UserInfo> logout(HttpServletRequest request) {
        StpUtil.logout(StpUtil.getLoginId(), StpUtil.getLoginDevice());
        return CommonResult.success();
    }


    /**
     * 生成默认密码
     *
     * @param user
     */
    @Override
    public void getDefaultPassword(UserInfo user) {
        String salt = UUID.randomUUID().toString();
        user.setSalt(salt);
        if (StringUtils.isNotEmpty(user.getPassWord()) && StringUtils.isNotBlank(user.getPassWord())) {
            String passWord = DigestUtils.md5DigestAsHex((user.getPassWord() + salt).getBytes());
            user.setPassWord(passWord);
        } else {
            String passWord = passwordDefault;
            user.setPassWord(DigestUtils.md5DigestAsHex((user.getPassWord() + salt).getBytes()));
        }
    }

    /**
     * 生成邀新二维码
     *
     * @return
     */
    @Override
    public CommonResult getQRCode() {
        try {
            UserInfo userInfo = userMapper.findById(StpUtil.getLoginIdAsString());
            if (ObjectUtil.isNotEmpty(userInfo)&& StrUtil.isNotEmpty(userInfo.getInvitedCode())) {
                String accessToken = WxUtils.getAccessToken(appid, secret);
                InputStream inputStream = WxUtils.getMiniProgramCode(accessToken, userInfo.getInvitedCode());
                String path = qiniuUtils.upload(inputStream, "小程序码"+IdUtil.simpleUUID());
                inputStream.close();
                return CommonResult.success(path);
            }
//            ByteArrayInputStream fileInputStream = QRCodeGenerator.generateQRCodeImage(url, 300, 300);
//            String fileName = IdUtil.simpleUUID();
//            String path = qiniuUtils.upload(fileInputStream, fileName);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return CommonResult.failed("分享码生成失败！");
    }

    @Override
    @Transactional
    public CommonResult updateEntityMoney(UserInfo userInfo) {
        try {
            if (StrUtil.isEmpty(userInfo.getId())) {
                return CommonResult.failed(ResultCodeEnum.PARAM_ERROR);
            }
            userInfo.setUpdateTime(DateUtil.now());
            //商家注册
            baseMapper.updateById(userInfo);
            return CommonResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(ResultCodeEnum.API_ERROR);
        }
    }
}
